package com.dgut.forum.interceptor;

import com.dgut.forum.config.AppConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${forum.login.url}")
    private String loginUrl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //找不到会话就返回null，不新建会话返回
        HttpSession session=request.getSession(false);
        if(session!=null&&session.getAttribute(AppConfig.USER_SESSION)!=null){
            log.info("拦截到请求,用户已经登录,执行后续代码");
            return true;
        }
        if(!loginUrl.startsWith("/")){
            loginUrl="/"+loginUrl;
        }
        response.sendRedirect(loginUrl);
        return false;
    }
}